// import setup from 'wpt-statistics';

import { matchByPathname } from '@packages/lib-router';
import * as libUrl from '@packages/lib-url';
import { uuid } from '@packages/lib-utils';

export const pageNameConfig = {
    /* 详情页 */
    // '/uri/D*': '/uri/*',
    // '/uri/:uri@J.*': '/uri/*',
    // '/webApp/auction/saleEdit': '/webApp/auction/saleEdit/*',
    // '/webApp/auction/saleEdit/:goodsId': '/webApp/auction/saleEdit/*',
};

export function getPageName(url = window.location.href) {
    const { router } = matchByPathname(libUrl.parse(url).pathname, WPT.router) || {};
    return `${window.location.origin}${pageNameConfig[router] || router}`;
}

class User {
    get userinfoSid() {
        return WPT.userinfo.userinfoSid || '';
    }

    get isNewUser() {
        return WPT.userinfo.isNewUser || 0;
    }

    get userinfoUri() {
        return WPT.userinfo.userinfoUri || this.fakeUserinfoUri;
    }

    get level() {
        return WPT.userinfo.memberLevel || 0;
    }
}

function getPageInfo() {
    return WPT.$curPage?.[0]?.info || {};
}

// const _send = setup(new User(), /w.weipaitang/.test(window.location.origin) && !WPT.debug && !process.env.LOCAL);
// const send = (data, options = {}) => {
//     const { retry = 1, timeout = 10000 } = options;
//     _send(
//         {
//             // finger: getFinger(),
//             ...getPageInfo(),
//             ...data,
//         },
//         { retry, timeout }
//     );
// };

let uniqueVisitId = `${Date.now()}${uuid()}`;

// 数据统计
function sendData(data = { type: 'visit' }, options = {}) {
    const { redirect = false, retry = 1 } = options;
    if (['visit', 'redirect301'].includes(data.route)) {
        if (!redirect) {
            uniqueVisitId = `${Date.now()}${uuid()}`;
        }
        if (data.otherData) {
            data.otherData = {
                ...data.otherData,
                visitId: uniqueVisitId,
            };
        } else {
            data.otherData = {
                visitId: uniqueVisitId,
            };
        }
    }
    // send(data, { retry });
}

// const timeOut = {}; // 定时器
WPT.exposureData = {
    key: {},
    datas: [], // 普通拍品
};

class TrottleNdeBounce {
    constructor(fn = () => undefined, trottleDelay = 5000, debounceDelay = 2000) {
        this.trottleDelay = trottleDelay; // 节流时间 、毫秒
        this.debounceDelay = debounceDelay; // 防抖动时间、毫秒
        this.recordTime = Date.now(); // 节流当前时间
        this.timeOut = 0;

        this.immeExposure = fn;
    }

    exec(...args) {
        this.debounce(this.immeExposure)(...args);
        this.trottle(this.immeExposure)(...args);
    }

    debounce = (fn = () => undefined) => (...args) => {
        window.clearTimeout(this.timeOut);
        this.timeOut = setTimeout(() => fn(...args), this.debounceDelay);
    };

    trottle = (fn = () => undefined) => (...args) => {
        if (Date.now() - this.recordTime > this.trottleDelay) {
            this.recordTime = Date.now();
            fn(...args);
        }
    };
}

class ExposureFactory {
    constructor(dataName) {
        WPT.exposureData[dataName] = {};
        this.dataName = dataName;
        this.Immediately = new TrottleNdeBounce(this.immeExposureData);
    }

    immeExposureData = (extraData) => {
        if (!this.hasCachedData) {
            return;
        }
        const { exposureData: exposureDatas = [] } = WPT.exposureData[this.dataName];
        const classify = this.classifyByType(exposureDatas); // 区分type类型上报

        Object.keys(classify).forEach((subTypeNid) => {
            const [subType, id = ''] = subTypeNid.split('-');
            for (let i = 0; i < classify[subTypeNid].length; i += 30) {
                // send({
                //     ...WPT.exposureData[this.dataName],
                //     exposureData: classify[subTypeNid].slice(i, i + 30),
                //     subType,
                //     extraData,
                //     ...(id && { id: Number(id) }),
                // });
            }
        });

        WPT.exposureData[this.dataName] = {};
    };

    delayExposureData = (key, data, extraData, options = {}) => {
        if (!WPT.exposureData.key[key]) {
            WPT.exposureData.key[key] = 1;

            if (!this.hasCachedData) {
                const { pageName, referrer, href } = options;
                WPT.exposureData[this.dataName] = {
                    exposureData: [data],
                    type: 'exposure',
                    href,
                    referrer,
                    pageName,
                };
            } else {
                WPT.exposureData[this.dataName].exposureData.push(data);
            }

            this.Immediately.exec(extraData);
        }
    };

    classifyByType = (exposureDatas = []) => {
        const classify = {};
        exposureDatas.forEach((i) => {
            classify[`${i.type}-${i.id || ''}`] = Array.prototype
                .concat(classify[[`${i.type}-${i.id || ''}`]], i)
                .filter((j) => j);
            i && i.id && delete i.id;
        });
        return classify;
    };

    get hasCachedData() {
        return WPT.exposureData[this.dataName].exposureData && WPT.exposureData[this.dataName].exposureData.length;
    }
}

// 普通拍品
const SaleExposure = new ExposureFactory('exposureData');
// 直播
const LiveExposure = new ExposureFactory('adData');

function quickUpData(data, extraData, { href, referrer, pageName }) {
    // send({
    //     exposureData: [data],
    //     extraData,
    //     type: 'exposure',
    //     subType: data.type || '',
    //     href,
    //     pageName,
    //     referrer,
    //     ...(data.id && { id: data.id }),
    // });
}

export default {
    sendData, // 普通上报
    // send, // 普通上报别名
    quickUpData, // 快速曝光上报
    delayExposureData: SaleExposure.delayExposureData, // 曝光上报
    immeExposureData: SaleExposure.immeExposureData, // 立即曝光上报
    delayExposureADData: LiveExposure.delayExposureData,
    immeExposureADData: LiveExposure.immeExposureData, // 直播广告立即上报
};
